#include <glib.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct _data_t {
    int i;
    char *s;
} data_t;

void print(void *data, void *user_data) {
    data_t *d = (data_t *)data;
    //printf("data%d=%s\n", d->i, d->s);
    g_print("data%d=%s\n", d->i, d->s);
}

int findcompare(void *data1, void *data2) {
    data_t *d1 = (data_t *)data1;
    data_t *d2 = (data_t *)data2;
    return strcmp(d1->s, d2->s);
}

#if 0
int main() {
    data_t d1, d2, d3, *d4, d5;
    d1.i = 5;
    d1.s = strdup("555");
    d2.i = 4;
    d2.s = strdup("444");
    d3.i = 3;
    d3.s = strdup("333");
    d4 = (data_t *)malloc(sizeof(data_t));
    d4->i = 2;
    d4->s = strdup("222");
    d5.i = 1;
    d5.s = strdup("111");
    GList *list = NULL;
    list = g_list_append(list, &d1);
    list = g_list_append(list, &d2);
    list = g_list_append(list, &d3);
    list = g_list_append(list, d4);
    list = g_list_append(list, &d5);
    //free(d4);
    /* print */
    g_list_foreach(list, (GFunc)print, NULL);
    /* find 1 */
    GList *fl1 = g_list_find(list, &d3);
    data_t *fd1 = (data_t *)fl1->next->data;
    g_print("find1->next: data%d=%s\n", fd1->i, fd1->s);
    /* find 2 */
    data_t temp = { 123, "222" };
    GList *fl2 = g_list_find_custom(list, &temp, (GCompareFunc)findcompare);
    data_t *fd2 = (data_t *)fl2->next->data;
    g_print("find2->next: data%d=%s\n", fd2->i, fd2->s);
    /* reverse */
    list = g_list_reverse(list);
    g_list_foreach(list, (GFunc)print, NULL);
    /* remove */
    GList *second = g_list_nth(list, 1);
    list = g_list_remove_link(list, second);
    g_list_foreach(list, (GFunc)print, NULL);
    g_list_free_1(second);
    /* remove and free */
    GList *third = g_list_nth(list, 1);
    list = g_list_delete_link(list, third);
    g_list_foreach(list, (GFunc)print, NULL);
    /* free memory */
    free(d1.s);
    free(d2.s);
    free(d3.s);
    free(d4->s);
    free(d5.s);
    free(d4);
    g_list_free(list);

    return 0;
}
#endif
